//! 查询相关

use crate::model::field;

use self::expr::QueryExprRightValue;

use super::{relation::JoinInfo, Meta};
pub mod expr;
pub mod method;

/// SQL查询表达式
#[derive(Debug)]
pub struct QueryBuilder<'a> {
    /// 基础表meta信息
    pub base_meta: Meta,
    /// 选择字段sql信息
    pub select_fields: Vec<String>,
    /// where相关sql语句信息
    pub wheres: Vec<String>,
    /// join表相关信息
    pub joins: Vec<JoinInfo>,
    /// 查询值
    pub values:Vec<&'a QueryExprRightValue<'a>>,
}
impl<'a> QueryBuilder<'a> {
    /// select join表的字段
    /// 
    /// # 参数说明
    /// 
    /// * field_index 对应join其他表的字段索引
    pub fn extra_select(self,field_index:u8)->Self{
        let field = &self.base_meta.field_list[field_index as usize];
        
;
        unimplemented!()
    }
    /// 获取where语句
    pub fn get_where_sql(&self) -> String {
        let sql = self.wheres.join(" ");
        if !sql.is_empty() {
            sql[1..sql.len() - 2].to_owned()
        } else {
            sql
        }
    }
    /// 获取join语句
    pub fn get_join_sql(&self) -> String {
        self.joins
            .iter()
            .map(|join| join.join_sql.clone())
            .collect::<Vec<String>>()
            .join(" ")
    }

    /// 获取select字段SQL语句
    pub fn get_select_field_sql(&self) -> String {
        if self.select_fields.is_empty() {
            self.base_meta
                .field_list
                .iter()
                .map(|field| format!("{}.{}", self.base_meta.table_name, field.table_field_name))
                .collect::<Vec<_>>()
                .join(",")
        } else {
            self.select_fields.join(",")
        }
    }

    /// 获取SELECT查询语句
    ///
    /// # 参数说明
    /// * beautify_format 是否对sql进行格式化排版为方便阅读格式
    pub fn get_select_sql(&self, beautify_format: bool) -> String {
        let sql = if self.joins.is_empty() {
            format!(
                "SELECT {} FROM {} WHERE {}",
                self.get_select_field_sql(),
                self.base_meta.table_name,
                self.get_where_sql()
            )
        } else {
            format!(
                "SELECT {} FROM {} {} WHERE {}",
                self.get_select_field_sql(),
                self.base_meta.table_name,
                self.get_join_sql(),
                self.get_where_sql()
            )
        };
        if beautify_format {
            sqlformat::format(
                &sql,
                &sqlformat::QueryParams::None,
                sqlformat::FormatOptions::default(),
            )
        } else {
            sql
        }
    }
}
/// 查询创建器
#[macro_export]
macro_rules! query {
    ( $( $x:expr ),* ) => {};
}
